﻿using EyFramework.Common;
using SqlSugar;
using System;

namespace EyFramework.ORM
{
    /// <summary>
    /// 使用HIS数据连接的数据库操作，并实现公共操作接口
    /// </summary>
    public class BaseDaoHis<T> : BaseDao<T>, IBaseHisDao<T> where T : class, new()
    {
        /// <summary>
        /// 实现获取那个数据库连接配置
        /// </summary>
        /// <returns></returns>
        public override string GetConnKey()
        {
            return Constants.CONNECT_TYPE_HIS;
        }

        /// <summary>
        /// 获取HIS的最大值
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="filedName"></param>
        /// <returns></returns>
        public long GetHisMaxId(string tableName, string fieldName)
        {
            var tableNameP = new SugarParameter(":sTbl_Nm", tableName.ToUpper());
            var filedNameP = new SugarParameter(":sCol_Nm", fieldName.ToUpper());
            var idO = new SugarParameter(":nReturn", null, true);
            var reslt = Db.Ado.UseStoredProcedure().SqlQuery<int>("PKG_SYS.GETMAXID", tableNameP, filedNameP, idO);
            return long.Parse(idO.Value.ToString());
        }

        /// <summary>
        /// 获取序列的最大值
        /// </summary>
        /// <param name="sequenceName"></param>
        /// <param name="createFlag"></param>
        /// <returns></returns>
        public long GetSequence(string sequenceName, bool createFlag = true)
        {
            try
            {
                return Db.Ado.GetLong("SELECT " + sequenceName + ".NEXTVAL FROM DUAL");
            }
            catch
            {
                if (createFlag)
                {
                    Db.Ado.ExecuteCommand("CREATE SEQUENCE " + sequenceName + " NOCYCLE NOCACHE");
                    return Db.Ado.GetLong("SELECT " + sequenceName + ".NEXTVAL FROM DUAL");
                }
                else
                {
                    throw;
                }
            }
        }

        public string GetCurrentDate(string formatStr = "YYYY-MM-DD HH24:MI:SS")
        {
            return Db.Ado.GetString("SELECT TO_CHAR(SYSDATE,:FORMATSTR ) FROM DUAL", new SugarParameter(":FORMATSTR", formatStr));
        }

        public void BeginTrans()
        {
            Db.Ado.BeginTran();
        }

        public void CommitTrans()
        {
            Db.Ado.CommitTran();
        }

        public void RollBackTrans()
        {
            Db.Ado.RollbackTran();
        }
    }
}